<?php
// $Id: newarlig.inc 51 2012-05-07 11:13:03Z ahmtsari@gmail.com $
/**
 * @file
 * Modules spesific funtions other than hooks. I is generated to reduce
 * main module file. So, it will be not included until they will be called.
 */

function newarlig_overview($op = 'list') {
    global $user;

    $sql = "SELECT g.game_time, g.home_team, g.away_team, g.home_score, g.away_score, "
        ."g.nid, p.home_score p_score1, p.away_score p_score2, p.prediction_score "
        ."FROM {game} g JOIN {game_prediction} p ON g.nid = p.nid "
        ."WHERE p.uid = %d AND g.saison_id = %d "
        ."UNION "
        ."SELECT g.game_time, g.home_team, g.away_team, g.home_score, g.away_score, "
        ."g.nid, NULL, NULL, 0 "
        ."FROM {game} g WHERE saison_id = %d AND nid NOT in (SELECT nid from {game_prediction} "
        ."WHERE uid = %d) ";
    switch ($op) {
        case 'edit':
            return newarlig_lig_predict(newarlig_lig_load(variable_get('newarlig_saison', 0)));
            $sql = "SELECT g.game_time, g.home_team, g.away_team, g.home_score, g.away_score, "
                ."g.nid, p.home_score p_score1, p.away_score p_score2, p.prediction_score "
                ."FROM {game} g JOIN {game_prediction} p ON g.nid = p.nid "
                ."WHERE p.uid = %d AND g.saison_id = %d AND g.game_time > " . time()
                ." UNION "
                ."SELECT g.game_time, g.home_team, g.away_team, g.home_score, g.away_score, "
                ."g.nid, NULL, NULL, 0 "
                ."FROM {game} g WHERE saison_id = %d AND nid NOT in (SELECT nid from {game_prediction} "
                ."WHERE uid = %d) "
                ." AND g.game_time > " . time()
                ." ORDER BY game_time";   
            $count_qry = "SELECT COUNT(*) FROM {game} WHERE saison_id = " 
                . variable_get('newarlig_saison', 0)
                ." AND game_time > " . time();            
            break;
        case 'list':
            $sql = "SELECT g.game_time, g.home_team, g.away_team, g.home_score, g.away_score, "
                ."g.nid, p.home_score p_score1, p.away_score p_score2, p.prediction_score "
                ."FROM {game} g JOIN {game_prediction} p ON g.nid = p.nid "
                ."WHERE p.uid = %d AND g.saison_id = %d AND g.game_time <= " . time()
                ." UNION "
                ."SELECT g.game_time, g.home_team, g.away_team, g.home_score, g.away_score, "
                ."g.nid, NULL, NULL, 0 "
                ."FROM {game} g WHERE saison_id = %d AND nid NOT in (SELECT nid from {game_prediction} "
                ."WHERE uid = %d) "
                ." AND g.game_time <= " . time()
                ." ORDER BY game_time DESC";       
            $count_qry = "SELECT COUNT(*) FROM {game} WHERE saison_id = " 
                . variable_get('newarlig_saison', 0)
                ." AND game_time <= " . time();            
            break;
    }
//    watchdog('newarlig_overview', $sql, WATCHDOG_DEBUG);
    $result = pager_query($sql, 9, 0, $count_qry, $user->uid, variable_get('newarlig_saison', 0), 
            variable_get('newarlig_saison', 0), $user->uid);
    $data = array();
    $rank = 1;
    while ($row = db_fetch_array($result)) {
        $game_time = $row['game_time'];
        $row['game_time'] = format_date($row['game_time']);
        if ($game_time > time()) {
            $node_obj = (object) $row;
            //Prediction form
            unset($row['home_score']);
            unset($row['away_score']);
            unset($row['p_score1']);
            unset($row['p_score2']);
            unset($row['prediction_score']);
            $row['form'] = array(
                'data' => drupal_get_form('newarlig_predict_table_form_' . $rank, $node_obj),
                'colspan' => 5,
            );
        }
        $nid = $row['nid'];
        unset($row['nid']);
        if (user_access('create game nodes')) {
            $node_url = url('node/'. $nid . '/edit');
            $data[] = array_merge(array("rank" => '<a href="' . $node_url . '">' . $rank++ . "</a>"), $row);
        } elseif (user_access('view game nodes')) {
            $node_url = url('node/'. $nid);
            $data[] = array_merge(array("rank" => '<a href="' . $node_url . '">' . $rank++ . "</a>"), $row);
        } else {
            $data[] = array_merge(array("rank" => $rank++), $row);
        }
        
    }
    $header = array(
        '#',
        t('Date'),
        t('Home Team'),
        t('Away Team'),
        array('data' => t('Skor'), 'colspan' => 2),
        array('data' => t('Pred.'), 'colspan' => 2),
        t('P.'),
    );
    $content = theme('table', $header, $data);
    if (user_access('create game nodes')) {
        $content = drupal_get_form('newarlig_table_form') . $content;
    }    
    return $content . theme('pager');
}

function newarlig_table_form ($form_state, $node = NULL) {
    $token = drupal_get_token() . '_form_state';
    if (isset($_SESSION[$token])) $form_state = $_SESSION[$token];
    $date_format = variable_get('newarlig_date_format', NEWARLIG_DATE_FORMAT);
    $form['#theme'] = 'newarlig_table_form';
    $form['#submit'][] = '_newarlig_table_form_submit';
    $form['game_time'] = array(
        '#type' => 'textfield',
        '#title' => t('Start Date/Time'),
        '#description' => t('When will the game start. Format: %time.',
            array('%time' => format_date(time(), 'custom', $date_format))),
        '#maxlength' => 25,
        '#default_value' => isset($form_state['values']['game_time']) ?
            $form_state['values']['game_time'] :
            format_date(time(), 'custom', $date_format),
    );
    if (module_exists('date_popup')) {
      // Make this a popup calendar widget if Date Popup module is enabled.
      $form['game_time']['#type'] = 'date_popup';
      $form['game_time']['#date_format'] = $date_format;
      $form['game_time']['#date_year_range'] = '0:+10';
      unset($form['game_time']['#description']);
      unset($form['game_time']['#maxlength']);
    }    
    $form['home_team'] = array(
        '#type' => 'textfield',
        '#title' => t('Home team'),
        '#description' => t('Enter home team of the game.'),
        '#size' => 30,
        '#maxlength' => 80,
    );
    $form['away_team'] = array(
        '#type' => 'textfield',
        '#title' => t('Away team'),
        '#description' => t('Enter away team of the game.'),
        '#size' => 30,
        '#maxlength' => 80,
    );    
    $form['saison_id'] = array('#type' => 'hidden', '#value' => variable_get('newarlig_saison', 0),);    
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Add'),
    );    
    return $form;
}

function theme_newarlig_table_form($form) {
    $output = '<table><tr><td>';
    $output .= drupal_render($form['game_time']) . '</td><td>';
    $output .= drupal_render($form['home_team']). '</td><td>';
    $output .= drupal_render($form['away_team']). '</td><td>';
    $output .= '<br/>' . drupal_render($form['submit']). '</td><td>';
    $output .= drupal_render($form). '</td></tr></table>';
    Return $output;
}

function _newarlig_table_form_submit ($form, $form_state) {
    global $user;
    // Create a new game node
    //$form_state = array();
    module_load_include('inc', 'node', 'node.pages');
    $node = array('type' => 'game');
    $form_state['values']['op'] = t('Save');
    $form_state['values']['name'] = $user->name;
    $token = drupal_get_token() . '_form_state';
    $_SESSION[$token] = $form_state;
    drupal_execute('game_node_form', $form_state, (object)$node);  
}
function newarlig_predict_table_form ($form_state, $node = NULL) {
    $form['#theme'] = 'newarlig_predict_table_form';
    $form['#submit'][] = '_newarlig_prediction_form_submit';
    $form['#validate'][] = '_newarlig_prediction_form_validate';
    $form['homescore'] = array(
        '#type' => 'textfield',
        '#size' => 2,
        '#default_value' => isset($node->p_score1) ? $node->p_score1 : '',
    );
   $form['awayscore'] = array(
        '#type' => 'textfield',
        '#size' => 2,
        '#default_value' => isset($node->p_score2) ? $node->p_score2 : '',
    );
    $form['nid'] = array(
        '#type' => 'hidden',
        '#value' => $node->nid,
    );
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => isset($node->p_score1) ? t('Update') : t('Predict'),
    );
    return $form;
}
function theme_newarlig_predict_table_form($form) {
    $output = '<table><tr><td>';
    $output .= drupal_render($form['homescore']) . '</td><td>';
    $output .= drupal_render($form['awayscore']). '</td><td>';
    $output .= drupal_render($form['submit']). '</td><td>';
    $output .= drupal_render($form). '</td></tr></table>';
    Return $output;
}

function theme_newarlig_node_predictions($items) {
    $output = '<hr/><h3>' . t('Predictors') . '</h3>';
    if (!empty($items)) {
        $output .= theme('table', array(t('User'), t('Home Score'), t('Away Score'), t('Prediction Score')), $items);
        $output .= theme('pager');
    }
    return $output;
}


/**
 * Page callback for displaying a competition overview.
 */
function newarlig_lig_predict($lig) {
    $sql = "SELECT g.game_time, g.home_team, g.away_team, g.home_score, g.away_score, g.nid "
        ."FROM {game} g WHERE g.saison_id = %d AND g.game_time > %d";
    $count_sql = "SELECT COUNT(*) "
        ."FROM {game} g WHERE g.saison_id = %d AND g.game_time > %d";
    $header = array(
        array('data' => t('Date'), 'field' => 'game_time', 'sort' => 'ASC'),
        array('data' => t('Home Team'), 'field' => 'home_team'),
        array('data' => t('Away Team'), 'field' => 'away_team'),
    );
    $q = pager_query($sql . tablesort_sql($header), 9, 0, $count_qry,  $lig->id, time());
    return drupal_get_form('newarlig_lig_prediction_form', $q) . theme('pager');
    
//    while ($r = db_fetch_array($q)) {
//        $rows[] = array(
//            format_date($r['game_time']),
//            $r['home_team'],
//            $r['away_team'],
//        );
//        
//    }    
//    if (!empty($rows)) {
//        $ret = theme('table', $header, $rows);
//    } else {
//        $ret = t('There are currently no matches defined for this competition.');
//    }
//    return $ret;    
}

function newarlig_lig_prediction_form($form_state, $q) {
    $form['#tree'] = TRUE;
    $form['notice']['#weight'] = -10;
    $form['notice']['#value'] = '<p>' . t('Use this table to submit your bets. ' .
      'Please remember to click the "@button" button before going to another page. ' .
      'Bets can be submitted until the match starts.',
      array('@button' => t('Predict'))) . '</p>';
    $alterable = FALSE;
    while ($r = db_fetch_array($q)) {
        $disabled = $r['game_time'] < time();
        if (!$disabled) {
          $alterable = TRUE;
        }        
        $prediction = _newarlig_prediction_load($r['nid']);
        $f = &$form['games'][$r['nid']];    
        $f['game_time'] = array(
          '#type' => 'hidden',
          '#value' => $r['game_time'],
        );             
        $f['time'] = array(
          '#type' => 'markup',
          '#prefix' => '<a href="' . url('node/'. $r['nid']) . '">', 
          '#suffix' => '</a>', 
          '#value' => format_date($r['game_time']),
        );        
        $f['home_team'] = array(
          '#value' => check_plain($r['home_team']),
        );        
        $f['bet_home'] = array(
          '#type' => 'textfield',
          '#size' => 4,
          '#maxlength' => 2,
          '#default_value' => $prediction->home_score,
          '#disabled' => $disabled,
        );        
        $f['score']['#value'] = $r['game_time'] < time()
            ? '<div style="text-align:center">'. t('@score_home : @score_away', array('@score_home' => $r['home_score'], '@score_away' => $r['away_score'])) . '</div>'
            : '<div style="text-align:center">'. '-' . '</div>';     
        $f['bet_away'] = array(
          '#type' => 'textfield',
          '#size' => 4,
          '#maxlength' => 2,
          '#default_value' => $prediction->away_score,
          '#disabled' => $disabled,
        );        
        $f['away_team'] = array(
          '#value' => check_plain($r['away_team']),
        );       
        $f['prediction_score'] = array(
          '#value' => '<div style="text-align:center">' . $prediction->prediction_score . '</div>',
        );           
    } 
    if (empty($form['games'])) {
        $form['notice'] = array(
            '#value' => t('There are no matches defined yet for this competition.'),
        );        
        return $form;
    }
//    $form['pager'] = array(
//        '#theme' => 'pager',
//        '#quantity' => 9,
//    );

    if ($alterable) {
        $form['games']['submit'] = array(
          '#type' => 'submit',
          '#value' => t('Predict'),
        );
    }    
    $form['games']['#theme'] = 'newarlig_lig_prediction_form';
    $header = array(
        array('data' => t('Time'), 'field' => 'game_time', 'sort' => 'asc'),
        array('data' => t('Home team'), 'colspan' => 2, 'field' => 'home_team'),
        t('Result'),
        array('data' => t('Away team'), 'colspan' => 2, 'field' => 'away_team'),
        t('Prediction Score'),
    );
    $form['games']['header'] = array(
        '#type' => 'value',
        '#value' => $header,
    );
    return $form;
}

function theme_newarlig_lig_prediction_form($form) {
  $rows = array();
  foreach (element_children($form['games']) as $id) {
    $row = array();
    foreach (element_children($form['games'][$id]) as $field) {
      if ($form['games'][$id][$field]['#type'] == 'hidden') continue;
      if ($cell = drupal_render($form['games'][$id][$field])) {
        $row[] = $cell;
      }
    }
    $rows[] = $row;
  }

  $theme['rows'] = $rows;
  $theme['attributes']['class'][] = 'predictiongame';
  if (isset($form['games']['header']['#value'])) {
    $theme['header'] = $form['games']['header']['#value'];
  }
  if (isset($form['empty']['#value'])) {
    $theme['empty'] = $form['empty']['#value'];
  }
  $output = drupal_render($form['notice']);
  $output .= theme('table', $theme['header'], $theme['rows']);  
  $output .= drupal_render($form);
  return $output;
}

function newarlig_lig_prediction_form_validate($form, &$form_state) {
    foreach (element_children($form_state['values']['games']) as $id) {
        if ($id == 'header') continue;
        if ($id == 'submit') continue;
        $game = $form_state['values']['games'][$id];
        if ($game['game_time'] < time()) {
            form_set_error('games', t('Game time: %time1. Sorry, your time (%time2) is up. You are too late!'
                , array('%time1' => fomat_date($game['game_time']), '%time2' => format_date(time()))));            
            break;
        } 
    }
}

function newarlig_lig_prediction_form_submit($form, $form_state) {
    global $user;
    
    foreach (element_children($form_state['values']['games']) as $id) {
        if ($id == 'header') continue;
        if ($id == 'submit') continue;
        $game = $form_state['values']['games'][$id];
        if ($game['game_time'] < time()) continue;
        if ($game['bet_home'] == $form['games'][$id]['bet_home']['#default_value'] 
         && $game['bet_away'] == $form['games'][$id]['bet_away']['#default_value']) continue;
        //save into predictions
        $form_state['values']['nid'] = (int)$id;
        $form_state['values']['homescore'] = $game['bet_home'];
        $form_state['values']['awayscore'] = $game['bet_away'];
        _newarlig_prediction_form_submit ($form, $form_state);
    }
}

function _newarlig_prediction_load($nid) {
    global $user;
    $result = db_query(
        'SELECT * FROM {game_prediction} WHERE nid = %d AND uid = %d', $nid, $user->uid
    );
    return db_fetch_object($result);    
}